package net.huashitong.appsecurity;

import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.security.SysPrincipal;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysRolePermissionService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.CollectionsUtils;
import com.sirdc.modules.utils.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.21
 */
public class AppRealm extends AuthorizingRealm {

    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @Override
    public boolean supports(AuthenticationToken token) {
        //仅支持appToken类型的Token
        return token instanceof AppToken;
    }

    /**
     * 认证流程
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        AppToken appToken = (AppToken) token;
        String username = appToken.getUsername();

        String tokenStr ="";//TODO 获取tonken字符串
        //url校验
        String urlParm = String.format("loginId=%s&timestamp=%s&token=%s",
                tokenStr, username, appToken.getTimestamp());
        String serverSign = MD5.md5(urlParm);

        SysLogin loginUser = sysLoginService.getById(username);
        SysUser userInfo = sysUserService.getById(username);
        return new SimpleAuthenticationInfo(new SysPrincipal(loginUser, userInfo),
                serverSign,
                getName());
    }

    /**
     * 授权流程
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户信息
        SysPrincipal principal = SysUserUtils.getSysPrincipal();
        String roleId = principal.getRoleId();
        String deptId = principal.getDeptId();

        //赋予权限信息
        List<String> permissions = sysRolePermissionService.queryPermissionByRoleIdDeptId(roleId, deptId);
        SysLogin user = sysLoginService.getById(principal.getUserId());
        if (user != null && CollectionsUtils.isNotEmpty(permissions)) {
            SimpleAuthorizationInfo info = constructInfo(permissions);//添加权限字符信息
            info.addRole(roleId);//添加角色
            return info;
        }
        return null;
    }


    /**
     * 构造用户的权限字符
     *
     * @param permissions
     * @return
     * @author: weihuang.peng
     */
    public SimpleAuthorizationInfo constructInfo(List<String> permissions) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (String permission : permissions) {
            if (StringUtils.isNotBlank(permission)) {
                info.addStringPermission(permission);//遍历添加用户的权限信息进入对象中
            }
        }
        //并更新用户的登陆时间，登陆日期等等参数
        return info;
    }


}
